"""输出格式化模块"""
from typing import Dict, Any, List
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich.columns import Columns
from collections import Counter
import json

class OutputFormatter:
    """结果输出格式化器"""
    
    def __init__(self, console: Console):
        self.console = console
    
    def display_results(self, results: Dict[str, Any], duration: float):
        """显示扫描结果"""
        
        scan_info = results['scan_info']
        scan_results = results['results']
        
        # 显示扫描统计
        self._display_statistics(scan_info, scan_results, duration)
        
        # 显示详细结果
        if scan_results:
            self._display_detailed_results(scan_results)
        else:
            self.console.print("\n[yellow]未发现开放的端口[/yellow]")
    
    def _display_statistics(self, scan_info: Dict[str, Any], 
                          results: Dict[str, Any], duration: float):
        """显示统计信息"""
        
        total_targets = len(scan_info['targets'])
        total_ports = len(scan_info['ports'])
        total_scans = total_targets * total_ports
        
        # 计算开放的端口
        open_ports = []
        for target_ports in results.values():
            open_ports.extend([p['port'] for p in target_ports])
        
        open_count = len(open_ports)
        
        # 服务分布统计
        services = []
        versions = []
        for target_ports in results.values():
            for port_info in target_ports:
                if port_info.get('service'):
                    services.append(port_info['service'])
                if port_info.get('version') and port_info['version'] != 'unknown':
                    versions.append(port_info['version'])
        
        service_counter = Counter(services)
        version_counter = Counter(versions)
        
        # 创建统计面板
        stats_table = Table(title="扫描统计", show_header=False)
        stats_table.add_column("指标", style="cyan")
        stats_table.add_column("数值", style="green")
        
        stats_table.add_row("扫描目标", str(total_targets))
        stats_table.add_row("扫描端口", str(total_ports))
        stats_table.add_row("总扫描数", str(total_scans))
        stats_table.add_row("开放端口", str(open_count))
        stats_table.add_row("耗时", f"{duration:.2f} 秒")
        
        if scan_info.get('stealth_mode'):
            stats_table.add_row("扫描模式", "隐蔽模式")
        if scan_info.get('bypass_enabled'):
            stats_table.add_row("绕过模式", "已启用")
        
        self.console.print(stats_table)
        
        # 显示服务分布
        if service_counter:
            service_table = Table(title="服务分布")
            service_table.add_column("服务", style="cyan")
            service_table.add_column("数量", style="green")
            service_table.add_column("比例", style="yellow")
            
            for service, count in service_counter.most_common():
                percentage = (count / len(services)) * 100
                service_table.add_row(
                    service, 
                    str(count), 
                    f"{percentage:.1f}%"
                )
            
            self.console.print(service_table)
        
        # 显示版本TOP5
        if version_counter:
            version_table = Table(title="版本TOP5")
            version_table.add_column("版本", style="cyan")
            version_table.add_column("数量", style="green")
            
            for version, count in version_counter.most_common(5):
                version_table.add_row(version, str(count))
            
            self.console.print(version_table)
    
    def _display_detailed_results(self, results: Dict[str, Any]):
        """显示详细结果"""
        
        # 为每个目标创建表格
        for target, ports in results.items():
            table = Table(title=f"目标: {target}")
            table.add_column("端口", style="cyan", justify="right")
            table.add_column("状态", style="green")
            table.add_column("服务", style="yellow")
            table.add_column("版本", style="blue")
            table.add_column("方法", style="magenta")
            table.add_column("响应时间", style="dim", justify="right")
            
            for port_info in sorted(ports, key=lambda x: x['port']):
                status_color = "green" if port_info['status'] == 'open' else "red"
                
                table.add_row(
                    str(port_info['port']),
                    f"[{status_color}]{port_info['status']}[/{status_color}]",
                    port_info.get('service', 'unknown'),
                    port_info.get('version', 'unknown'),
                    port_info.get('method', 'unknown'),
                    f"{port_info.get('response_time', 0):.3f}s"
                )
            
            self.console.print(table)
    
    def export_json(self, results: Dict[str, Any], filename: str):
        """导出结果为JSON格式"""
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)
    
    def export_csv(self, results: Dict[str, Any], filename: str):
        """导出结果为CSV格式"""
        import csv
        
        with open(filename, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['Target', 'Port', 'Status', 'Service', 'Version', 'Method'])
            
            for target, ports in results['results'].items():
                for port_info in ports:
                    writer.writerow([
                        target,
                        port_info['port'],
                        port_info['status'],
                        port_info.get('service', 'unknown'),
                        port_info.get('version', 'unknown'),
                        port_info.get('method', 'unknown')
                    ])
